package com.sliverhark.filter;

import com.sliverhark.domain.LoginUser;
import com.sliverhark.utils.JwtUtil;
import com.sliverhark.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache rediscache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String userid;

        // 获取token
        String token = request.getHeader("token");
        if(StringUtils.isBlank(token)){
            // 放行
            filterChain.doFilter(request, response);
            return;
        }   

        // 解析token
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userid = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法!");
        }

        // 从redis中获取用户信息
        String redisKey = "login:" + userid;
        LoginUser loginUser = rediscache.getCacheObject(redisKey);
        if(Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登陆");
        }
        // 存入SecurityContextHolder
        // TODO: 获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        // 将authenticationToken (token) 封装到LocalThread当中去, 为了后面请求(request)检测是否带有token,
        // 从而判断请求的合理, 是否用户登录
        // TODO: 如何绕过filter, 后续请求不需要使用token
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        // 放行
        filterChain.doFilter(request, response);

     }
}
